package com.frejoys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.common.enums.EStoreUserType;
import com.frejoys.dao.entity.StoreUser;
import com.frejoys.dao.mapper.StoreUserMapper;
import com.frejoys.service.StoreUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class StoreUserServiceImpl extends ServiceImpl<StoreUserMapper, StoreUser> implements StoreUserService {
    @Override
    public boolean addInfo(Long userId, Integer storeId, Integer role) {
        return save(new StoreUser(){{
            setUserId(userId);
            setStoreId(storeId);
            setRole(role);
        }});
    }

    @Override
    public boolean upInfo(Integer id, Long userId, Integer storeId, Integer role) {

        LambdaUpdateWrapper<StoreUser> wrapper = new UpdateWrapper().lambda();
        wrapper.eq(StoreUser::getId, id);

        if (userId!=null) {
            wrapper.set(StoreUser::getUserId, userId);
        }
        if (storeId!=null) {
            wrapper.set(StoreUser::getStoreId, storeId);
        }
        if (role!=null) {
            wrapper.set(StoreUser::getRole, role);
        }
        return update(wrapper);
    }

    @Override
    public List<Integer> getStoreIdByUserId(Long userId) {
        LambdaQueryWrapper<StoreUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(StoreUser::getStoreId);
        wrapper.eq(StoreUser::getUserId, userId);
        List<StoreUser> storeUsers = baseMapper.selectList(wrapper);
        return storeUsers.stream().map(StoreUser::getStoreId).collect(Collectors.toList());
    }

    @Override
    public Long getStoreOwnerUserId(Integer storeId) {
        LambdaQueryWrapper<StoreUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(StoreUser::getUserId);
        wrapper.eq(StoreUser::getStoreId, storeId).eq(StoreUser::getRole, EStoreUserType.owner.getValue());
        StoreUser m = getOnly(wrapper);
        return m != null ? m.getUserId() : null;
    }


}
